package com.baizhi.config.shiro;

import com.baizhi.entity.Admin;
import com.baizhi.mapper.AdminMapper;
import com.baizhi.service.CmfzShiroService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Set;

public class AuthorRealm extends AuthorizingRealm {
    @Autowired
    private AdminMapper adminMapper;
    @Autowired
    private CmfzShiroService cmfzShiroService;
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        /**
         * 多身份 手机号 邮箱 账号
         * getPrimaryPrincipal() 获取账号
         */
//        1.获取用户名
        String username = principalCollection.getPrimaryPrincipal().toString();
//        2.查询授权信息
        Set<String> roles = cmfzShiroService.selectRoleNameByUsername(username);
        Set<String> permissions = cmfzShiroService.selectPermissionByUsername(username);
//        3.封装info返回
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        info.addRoles(roles);
        info.addStringPermissions(permissions);

        return info;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        UsernamePasswordToken token = (UsernamePasswordToken)authenticationToken;
        String username = token.getUsername();
        Admin admin = adminMapper.selectByName(username);
        if(admin!=null){
            ByteSource salt = ByteSource.Util.bytes(admin.getSalt());
            return new SimpleAuthenticationInfo(admin.getUserName(),admin.getPassword(),salt,this.getName());
        }
        return null;
    }
}
